<?php namespace Phpcmf\Model\Favorite;

// 自动执行方法
class Op extends \Phpcmf\Model
{

    public function is_favorite($tablename, $dirname) {

        if (!dr_in_array('favorites', \Phpcmf\Service::M('table')->get_cache_field($tablename)) ) {
            return dr_return_data(0, dr_lang('应用[模块内容收藏]未安装到本模块[%s]', $dirname));
        }

        $id = (int)\Phpcmf\Service::L('input')->get('id');

        if (!$this->uid) {
            return dr_return_data(0, dr_lang('还没有登录'));
        } elseif (!$id) {
            return dr_return_data(0, dr_lang('id参数不完整'));
        }

        $favorite = $this->db->table($tablename.'_favorite')->where('cid', $id)->where('uid', $this->uid)->countAllResults();
        if ($favorite) {
            return dr_return_data(1, dr_lang('已经收藏'));
        } else {
            return dr_return_data(0, dr_lang('没有收藏'));
        }
    }
    
    public function run($tablename, $dirname) {

        if (!dr_in_array('favorites', \Phpcmf\Service::M('table')->get_cache_field($tablename)) ) {
            return dr_return_data(0, dr_lang('应用[模块内容收藏]未安装到本模块[%s]', $dirname));
        }

        $id = (int)\Phpcmf\Service::L('input')->get('id');
        if (!$this->uid) {
            return dr_return_data(0, dr_lang('还没有登录'));
        } elseif (!$id) {
            return dr_return_data(0, dr_lang('id参数不完整'));
        }

        $data = $this->db->table($tablename.'_index')->where('id', $id)->countAllResults();
        if (!$data) {
            return dr_return_data(0, dr_lang('模块内容不存在'));
        }

        $table = $tablename.'_favorite';
        if (!$this->db->tableExists($table) ) {
            return dr_return_data(0, dr_lang('应用[模块内容收藏]未安装到本模块[%s]', $dirname));
        }

        $favorite = $this->db->table($table)->where('cid', $id)->where('uid', $this->uid)->get()->getRowArray();
        if ($favorite) {
            // 已经收藏了,我们就删除它
            $msg = dr_lang('取消收藏');
            $this->db->table($table)->where('id', intval($favorite['id']))->delete();
        } else {
            if (!\Phpcmf\Service::M()->db->fieldExists('inputtime', $table)) {
                \Phpcmf\Service::M()->query('ALTER TABLE `'.$table.'` ADD `inputtime` int(10) unsigned DEFAULT \'0\' COMMENT \'操作时间\';');
            }
            $msg = dr_lang('收藏成功');
            $this->db->table($table)->insert(array(
                'cid' => $id,
                'uid' => $this->uid,
                'inputtime' => SYS_TIME
            ));
        }

        // 更新数量
        $c = $this->db->table($tablename.'_favorite')->where('cid', $id)->countAllResults();
        $this->db->table($tablename)->where('id', $id)->set('favorites', $c)->update();
        \Phpcmf\Service::M('cache')->update_data_cache();

        // 返回结果
        return dr_return_data(1, $msg, $c);

    }


}